<template>
  <el-table
      v-loadmore="myLoad"
      size="large"
      :data="data.co"
      max-height="530"
      style="width: 100%"
  >
    <template #empty>
      <el-skeleton v-if="isLoading" :rows="5" animated/>
      <span v-else>暂无数据</span>
    </template>
    <el-table-column label="标题" prop="title" min-width="100px"/>

      <el-table-column label="描述" prop="description" min-width="150px"/>



    <el-table-column label="任务附件" prop="taskfile" min-width="100px">
      <template #default="scope">
        <el-link v-if="scope.row.taskfile" type="primary" @click="downloadFile(scope.row.id, scope.row.taskfile)">
          任务附件
        </el-link>
        <span v-else>无任务文件</span>
      </template>
    </el-table-column>

    <el-table-column label="结果附件" prop="file" min-width="100px">
      <template #default="scope">
        <el-link v-if="scope.row.resultfile" type="primary" @click="downloadFile(scope.row.id, scope.row.resultfile)">
          下载附件
        </el-link>
        <span v-else>无附件</span>
      </template>
    </el-table-column>
    <el-table-column label="任务状态" prop="file" min-width="150px">
      <template #default="scope">
        <el-tag v-if="scope.row.status === 0" type="info">未提交</el-tag>
        <el-tag v-else-if="scope.row.status === 2" type="warning">待审核</el-tag>
        <el-tag v-else-if="scope.row.status === 3" type="success">已通过</el-tag>
        <el-tag v-else-if="scope.row.status === 4" type="danger">未通过</el-tag>
      </template>
    </el-table-column>
    <el-table-column label="创建时间" prop="created_at" min-width="150px">
      <template #default="scope">
        <span>{{ scope.row.createdAt   }}</span>
      </template>
    </el-table-column>

    <el-table-column label="更新时间" prop="updated_at" min-width="150px">
      <template #default="scope">
        <span>{{ scope.row.updatedAt }}</span>
      </template>
    </el-table-column>
    <el-table-column label="操作" width="300">
      <template #default="scope">
        <el-button size="small"  @click="openDetailDialog(scope.row.id)">查看详情</el-button>
        <el-button size="small" type="primary" @click="openUploadDialog(scope.row)">上传结果附件</el-button>
      </template>
    </el-table-column>
    <template #append>
      <p v-if="isLoading">
        <el-divider content-position="center">加载中...</el-divider>
      </p>
      <p v-if="isNot">
        <el-divider content-position="center">到底了</el-divider>
      </p>
    </template>
  </el-table>

  <!-- 上传结果附件对话框 -->
  <el-dialog
    v-model="uploadDialogVisible"
    title="上传结果附件"
    width="500px"
    center
    @closed="resetUploadDialog"
  >
    <div class="upload-content">
      <div class="task-info">
        <h4>任务信息</h4>
        <p><strong>标题：</strong>{{ currentTask.title }}</p>
        <p><strong>描述：</strong>{{ currentTask.description }}</p>
      </div>
      
      <el-divider></el-divider>
      
      <div class="upload-section">
        <h4>上传附件</h4>
        <el-upload
          ref="upload"
          class="upload-demo"
          :auto-upload="false"
          :on-change="handleFileChange"
          :on-exceed="handleFileExceed"
          :limit="1"
          :file-list="data.fileList"
          drag
        >
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">
            将文件拖到此处，或<em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              支持上传单个文件
            </div>
          </template>
        </el-upload>
      </div>
    </div>
    <el-button @click="uploadDialogVisible = false">取消</el-button>
    <el-button
      type="primary"
      @click="submitUpload"
      :disabled="!data.file"
      :loading="uploadLoading"
    >
      提交
    </el-button>
    

  </el-dialog>

  <!-- 任务详情对话框 -->
  <TaskDetailDialog ref="taskDetailDialogRef" />
</template>

<script setup>
import {reactive, onMounted, inject, ref} from 'vue'
import {useRoute} from 'vue-router'
import {ElMessage} from 'element-plus'
import {UploadFilled} from '@element-plus/icons-vue'
import {useStore} from '@/store'
import {downloadTaskFile, getTaskList, uploadFile} from "@/components/userTable/task"
import TaskDetailDialog from './TaskDetailDialog.vue'
import Cookies from "js-cookie";

const userStore = useStore()
const route = useRoute()

// 对话框相关状态
const uploadDialogVisible = ref(false)
const currentTask = ref({})
const uploadLoading = ref(false)
const taskDetailDialogRef = ref(null)

// 打开上传对话框
const openUploadDialog = (row) => {
  currentTask.value = row
  uploadDialogVisible.value = true
}

// 重置上传对话框
const resetUploadDialog = () => {
  data.file = null
  data.fileList = []
  upload.value?.clearFiles()
  uploadLoading.value = false
}

// 打开任务详情对话框
const openDetailDialog = (taskId) => {
  taskDetailDialogRef.value?.openDialog(taskId)
}

// 提交上传
const submitUpload = () => {
  if (!data.file) {
    ElMessage.error('请先选择文件')
    return
  }
  
  uploadLoading.value = true
  const formData = new FormData()
  formData.append("user_id", Cookies.get('yourStuNum'))
  formData.append("file", data.file)
  
  uploadFile(currentTask.value.id, formData).then((res) => {
    if (res.status === "success") {
      ElMessage.success("提交成功")
      uploadDialogVisible.value = false
      getArticle()
    }
  }).catch(() => {
    ElMessage.error("提交失败")
  }).finally(() => {
    uploadLoading.value = false
  })
}
const upload = ref(null)

function handleFileExceed(files) {
  upload.value?.clearFiles()
  const file = files[0]
  upload.value?.handleStart(file)
  data.file = file
}

function handleFileChange(file) {
  data.file = file.raw
  data.fileList = [file]
}
const isPhone = inject('isPhone')
const isLoading = ref(true)
const isNot = ref(false)
const isMyself = inject('isMyself')
const value = ref('')
const data = reactive({
  co: [],
  fileList: [],
  file: null,
  articleType: [],
  tagType: [],
  search: '',
  beg: 1,
  end: 10,
  index: 0,
  yeshu: 1,
})
onMounted(() => {
  getArticle()
})

// 下载文件
const downloadFile = (taskId, fileName) => {
  downloadTaskFile(taskId).then((response) => {

    // 使用正则表达式提取文件名
    const filename = fileName.match(/[^/]+$/)[0];

    const url = window.URL.createObjectURL(new Blob([response]));
    const link = document.createElement("a");
    link.href = url;
    link.setAttribute("download", filename);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  });
};

function getArticle() {
  isLoading.value = true
  isNot.value = false

  getTaskList({
    page: data.beg,
    limit: data.end,
    user_id: route.params.id || userStore.userInfo.id,
  })
      .then(res => {
        data.co = res.tasks || []
        // data.articleType = res.data.collectType || []
        // data.tagType = data.articleType.map(item => {
        //   return { label: item.name, value: item.id + '' }
        // })
        isLoading.value = false
        if (0 < data.co.length && data.co.length < data.yeshu * 10) {
          isNot.value = true
        }
      })
}


const handleEdit = (index, row) => {
  console.log(index, row)
}

const handleDelete = (index, row) => {
  console.log(index, row)
}

function myChange(val) {
  data.search = ''
  if (val == '') {
    val = 0
  }
  data.yeshu = 1
  data.index = val
  getArticle()
}

function mySearch() {
  if (data.search == '') {
    ElMessage({
      showClose: true,
      message: '请输入关键字',
      type: 'error',
    })
  } else {
    getSearchData()
  }
}

// function getSearchData() {
//   isLoading.value = true
//   isNot.value = false
//         value: data.search,
//         id: route.params.id || userStore.userInfo.id,
//         // route.params.id || store.state.userInfo.id
//       })
//       .then(res => {
//         data.co = res.data
//         isLoading.value = false
//         if (0 < data.co.length && data.co.length < data.yeshu * 10) {
//           isNot.value = true
//         }
//       })
// }

const myLoad = () => {
  if (!isNot.value) {
    if (data.search == '') {
      data.end += 10
      data.yeshu++
      getArticle()
    } else {
      data.end += 10
      data.yeshu++
      getSearchData()
    }
  }
}
</script>

<style scoped>
.upload-content {
  padding: 20px 0;
}

.task-info {
  margin-bottom: 20px;
}

.task-info h4 {
  margin: 0 0 15px 0;
  color: #303133;
  font-size: 16px;
}

.task-info p {
  margin: 8px 0;
  color: #606266;
  line-height: 1.5;
}

.upload-section h4 {
  margin: 0 0 15px 0;
  color: #303133;
  font-size: 16px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.upload-demo {
  width: 100%;
}
</style>
